import { store } from "@/store";
import { defineStore } from "pinia";
import { storageLocal } from "@pureadmin/utils";
import { PLATFORM_Map, UNIT_TYPE_VIEW_Map } from "@/constant/index";
import { getUnitTree as getOperateUnitTree } from "@/api/operate/unity-management/index";
import { getUnitTree as getManagerUnitTree } from "@/api/manage/units-manager/units-manager/index";
import { removeToken } from "@/utils/auth";
import { userKey } from "@/utils/auth";
import { getScreenUnitTree } from "@/api/screen";
import { message } from "@/utils/message";
import { getProjectList } from "@/api/operate/project-management/projectManagement";

type manageType = {
  /** 当前单位id */
  unityId: number;
  /** 当前查看类型 */
  views: number;
  /** 当前单位名称 */
  unityName: string;
};
type operateType = {
  /** 当前选中项目id */
  checkedProject: number;
  /** 当前选中单位id */
  checkedUnitId: number;
  /** 当前选中单位id路径 */
  checkedUnitPath: string;
  /** 当前查看类型 */
  views: number;
  /** 当前单位名称 */
  unityName: string;
  /** 当前项目名称 */
  projectName: string;
  /** 当前项目权限 */
  openFunc: number[];
};
type screenType = {
  /** 当前选中单位 */
  unit: any;
  /** 当前选中项目 */
  project: any;
  /** 当前查看类型 */
  views: number;
};

export const usePageVariablesStore = defineStore({
  id: "page-variables",
  state: () => ({
    /** 平台类型 */
    platform: null,
    /** 管理平台变量 */
    manage: null as manageType,
    /** 运营平台变量 */
    operate: null as operateType,
    operateProjectInfo: null as any,
    operateUnitList: [] as any[],
    manageUnitList: [] as any[],
    router: null as any,
    /** 大屏变量 */
    screen: null as screenType,
    screenUnitList: [] as any[],
    messagenew: 1
  }),
  actions: {
    /** 设置平台 */
    setPlatform(platform: number) {
      this.platform = platform;
      storageLocal().setItem("platform", platform);
    },
    /** 获取当前平台 */
    getPlatform(): PLATFORM_Map {
      if (!this.platform) {
        if (!storageLocal().getItem("platform")) {
          if (storageLocal().getItem(userKey)?.userInfo?.allowPortal) {
            let allowPortal =
              storageLocal().getItem(userKey).userInfo.allowPortal;
            if (allowPortal.includes(PLATFORM_Map.data)) {
              this.setPlatform(PLATFORM_Map.data);
            } else if (allowPortal.includes(PLATFORM_Map.manage)) {
              this.setPlatform(PLATFORM_Map.manage);
            } else if (allowPortal.includes(PLATFORM_Map.operate)) {
              this.setPlatform(PLATFORM_Map.operate);
            }
          } else {
            return
          }
        } else {
          this.platform = storageLocal().getItem("platform");
        }
      }
      return this.platform;
    },
    /** 设置管理平台 */
    setManage(manage: manageType) {
      this.manage = manage;
      storageLocal().setItem("manage", manage);
    },
    /** 获取管理平台 */
    getManage(): manageType {
      // console.log('记得放开退出登录！');
      if (!this.manage) {
        if (!storageLocal().getItem("manage")) {
          this.setManage({
            unityId: this.manageUnitList[0]?.id
              ? this.manageUnitList[0]?.id
              : null,
            unityName: this.manageUnitList[0]?.unityName
              ? this.manageUnitList[0]?.unityName
              : null,
            views: UNIT_TYPE_VIEW_Map.current
          });
        } else {
          this.manage = storageLocal().getItem("manage");
        }
      }
      if (
        this.manageUnitList?.length != 0 &&
        !getUnitIds(this.manageUnitList).includes(this.manage.unityId)
      ) {
        nextTick(() => {
          logout();
        });
      }
      let newUnitName = getUnitName(this.manageUnitList, this.manage.unityId);
      if (this.manage.unityName != newUnitName) {
        this.setManage({
          unityId: this.manage.unityId,
          unityName: newUnitName,
          views: this.manage.views
        });
      }
      return this.manage;
    },
    /** 设置运营平台 */
    setOperate(operate: operateType) {
      this.operate = operate;
      storageLocal().setItem("operate", operate);
      // window.location.reload();
    },
    /** 获取运营平台 */
    getOperate(): operateType {
      // console.log('记得放开退出登录！');
      if (!this.operate) {
        if (!storageLocal().getItem("operate")) {
          this.setOperate({
            checkedProject: null,
            checkedUnitId: this.operateUnitList[0]?.id
              ? this.operateUnitList[0]?.id
              : null,
            checkedUnitPath: this.operateUnitList[0]?.id
              ? this.operateUnitList[0]?.id + ""
              : null,
            views: UNIT_TYPE_VIEW_Map.current,
            unityName: this.operateUnitList[0]?.unityName
              ? this.operateUnitList[0]?.unityName
              : null,
            projectName: null,
            openFunc: this.operateUnitList[0]?.openFunc
              ? this.operateUnitList[0]?.openFunc
              : []
          });
        } else {
          this.operate = storageLocal().getItem("operate");
        }
      }
      if (
        this.operateUnitList?.length != 0 &&
        !getUnitIds(this.operateUnitList).includes(this.operate.checkedUnitId)
      ) {
        nextTick(() => {
          logout();
        });
      }
      let newUnitName = getUnitName(
        this.operateUnitList,
        this.operate.checkedUnitId
      );
      if (this.operate.unityName != newUnitName) {
        this.setOperate({
          checkedProject: this.operate.checkedProject,
          checkedUnitId: this.operate.checkedUnitId,
          checkedUnitPath: this.operate.checkedUnitPath,
          views: this.operate.views,
          unityName: newUnitName,
          projectName: this.operate.projectName,
          openFunc: this.operate.openFunc
        });
      }
      return this.operate;
    },
    /** 清空缓存 */
    clear() {
      this.platform = null;
      this.manage = null;
      this.operate = null;
      this.operateUnitList = [];
      this.manageUnitList = [];
    },
    /** 设置管理平台单位名称 */
    setManageUnitName(unitName: string) {
      this.manage.unityName = unitName;
      storageLocal().setItem("manage", this.manage);
    },
    /** 设置运营平台项目名称 */
    setOperateProjectName(projectName: string) {
      this.operate.projectName = projectName;
      storageLocal().setItem("operate", this.operate);
    },
    /** 设置运营平台开通权限 */
    setOperateOpenFunc(openFunc: number[]) {
      this.operate.openFunc = openFunc;
      storageLocal().setItem("operate", this.operate);
    },
    /** 设置运营平台单位名称 */
    setOperateUnitName(unitName: string) {
      this.operate.unityName = unitName;
      storageLocal().setItem("operate", this.operate);
    },
    /** 设置大屏 */
    setScreen(screen: screenType) {
      this.screen = screen;
      storageLocal().setItem("screen", screen);
    },
    /** 获取大屏 */
    getScreen(): screenType {
      if (!this.screen) {
        if (!storageLocal().getItem("screen")) {
          this.setScreen({
            unit: this.screenUnitList[0],
            project: null,
            views: UNIT_TYPE_VIEW_Map.current
          });
        } else {
          this.screen = storageLocal().getItem("screen");
        }
      }
      return this.screen;
    }
  }
});
/** 加载所有单位树 */
export const initUnit = () =>
  new Promise((resolve, reject) => {
    usePageVariablesStore(store).router = useRouter();
    initOperateUnit()
      .then(res => {
        initManageUnit()
          .then(res => {
            initScreenUnit()
              .then(res => {
                resolve("");
              })
              .catch(err => {
                reject(err);
              });
          })
          .catch(err => {
            reject(err);
          });
      })
      .catch(err => {
        reject(err);
      });
  });
/** 加载运营单位树 */
export const initOperateUnit = () =>
  new Promise((resolve, reject) => {
    getOperateUnitTree()
      .then(res => {
        let pageVariablesStore = usePageVariablesStore(store);
        pageVariablesStore.operateUnitList = res.result.data;
        if (res.result.data == null || res.result.data.length == 0) {
          message("当前登录用户暂无被授权单位！", { type: "error" });
          removeToken();
          storageLocal().removeItem("closeAutoPopUp");
          reject("");
          return
        }
        if (!storageLocal().getItem("operate")) {
          pageVariablesStore.setOperate({
            checkedProject: null,
            checkedUnitId: pageVariablesStore.operateUnitList[0]?.id
              ? pageVariablesStore.operateUnitList[0]?.id
              : null,
            checkedUnitPath: pageVariablesStore.operateUnitList[0]?.id
              ? pageVariablesStore.operateUnitList[0]?.id + ""
              : null,
            views: UNIT_TYPE_VIEW_Map.current,
            unityName: pageVariablesStore.operateUnitList[0]?.unityName
              ? pageVariablesStore.operateUnitList[0]?.unityName
              : null,
            projectName: null,
            openFunc: []
          });
        } else {
          pageVariablesStore.operate = storageLocal().getItem("operate");
        }
        if (
          pageVariablesStore.operateUnitList?.length != 0 &&
          !getUnitIds(pageVariablesStore.operateUnitList).includes(
            pageVariablesStore.operate.checkedUnitId
          )
        ) {
          pageVariablesStore.setOperate({
            checkedProject: null,
            checkedUnitId: pageVariablesStore.operateUnitList[0]?.id
              ? pageVariablesStore.operateUnitList[0]?.id
              : null,
            checkedUnitPath: pageVariablesStore.operateUnitList[0]?.id
              ? pageVariablesStore.operateUnitList[0]?.id + ""
              : null,
            views: UNIT_TYPE_VIEW_Map.current,
            unityName: pageVariablesStore.operateUnitList[0]?.unityName
              ? pageVariablesStore.operateUnitList[0]?.unityName
              : null,
            projectName: null,
            openFunc: pageVariablesStore.operateUnitList[0]?.openFunc
              ? pageVariablesStore.operateUnitList[0]?.openFunc
              : null
          });
        }
        let newUnitName = getUnitName(
          pageVariablesStore.operateUnitList,
          pageVariablesStore.operate.checkedUnitId
        );
        if (pageVariablesStore.operate.unityName != newUnitName) {
          pageVariablesStore.setOperate({
            checkedProject: pageVariablesStore.operate.checkedProject,
            checkedUnitId: pageVariablesStore.operate.checkedUnitId,
            checkedUnitPath: pageVariablesStore.operate.checkedUnitPath,
            views: pageVariablesStore.operate.views,
            unityName: newUnitName,
            projectName: pageVariablesStore.operate.projectName,
            openFunc: pageVariablesStore.operate.openFunc
          });
        }
        resolve(res.result.data);
      })
      .catch(err => {
        reject(err);
      });
  });
/** 加载管理单位树 */
export const initManageUnit = () =>
  new Promise((resolve, reject) => {
    getManagerUnitTree()
      .then(res => {
        let pageVariablesStore = usePageVariablesStore(store);
        pageVariablesStore.manageUnitList = res.result.data;
        if (res.result.data == null || res.result.data.length == 0) {
          message("当前登录用户暂无被授权单位！", { type: "error" });
          removeToken();
          storageLocal().removeItem("closeAutoPopUp");
          reject("");
          return
        }
        if (!storageLocal().getItem("manage")) {
          pageVariablesStore.setManage({
            unityId: pageVariablesStore.manageUnitList[0]?.id
              ? pageVariablesStore.manageUnitList[0]?.id
              : null,
            unityName: pageVariablesStore.manageUnitList[0]?.unityName
              ? pageVariablesStore.manageUnitList[0]?.unityName
              : null,
            views: UNIT_TYPE_VIEW_Map.current
          });
        } else {
          pageVariablesStore.manage = storageLocal().getItem("manage");
        }
        if (
          pageVariablesStore.manageUnitList?.length != 0 &&
          !getUnitIds(pageVariablesStore.manageUnitList).includes(
            pageVariablesStore.manage.unityId
          )
        ) {
          pageVariablesStore.setManage({
            unityId: pageVariablesStore.manageUnitList[0]?.id
              ? pageVariablesStore.manageUnitList[0]?.id
              : null,
            unityName: pageVariablesStore.manageUnitList[0]?.unityName
              ? pageVariablesStore.manageUnitList[0]?.unityName
              : null,
            views: UNIT_TYPE_VIEW_Map.current
          });
        }
        let newUnitName = getUnitName(
          pageVariablesStore.manageUnitList,
          pageVariablesStore.manage.unityId
        );
        if (pageVariablesStore.manage.unityName != newUnitName) {
          pageVariablesStore.setManage({
            unityId: pageVariablesStore.manage.unityId,
            unityName: newUnitName,
            views: pageVariablesStore.manage.views
          });
        }
        resolve(res.result.data);
      })
      .catch(err => {
        reject(err);
      });
  });
/** 加载大屏单位树 */
export const initScreenUnit = () =>
  new Promise((resolve, reject) => {
    getScreenUnitTree().then(res => {
      let pageVariablesStore = usePageVariablesStore(store);
      pageVariablesStore.setScreen(null);
      pageVariablesStore.screenUnitList = res.result.data;
      if (res.result.data == null || res.result.data.length == 0) {
        message("当前登录用户暂无被授权单位！", { type: "error" });
        removeToken();
        storageLocal().removeItem("closeAutoPopUp");
        reject("");
        return
      }
      if (!storageLocal().getItem("screen")) {
        pageVariablesStore.setScreen({
          unit: res.result.data[0],
          project: null,
          views: UNIT_TYPE_VIEW_Map.current
        });
      } else {
        pageVariablesStore.screen = storageLocal().getItem("screen");
      }
      if (
        pageVariablesStore.screenUnitList?.length != 0 &&
        !getUnitIds(pageVariablesStore.screenUnitList).includes(
          pageVariablesStore?.screen?.unit?.id
        )
      ) {
        pageVariablesStore.setScreen({
          unit: pageVariablesStore.screenUnitList[0],
          project: null,
          views: UNIT_TYPE_VIEW_Map.current
        });
      }
      let newUnitName = getUnitName(
        pageVariablesStore.screenUnitList,
        pageVariablesStore.screen?.unit?.id
      );
      if (pageVariablesStore.screen.unit.unityName != newUnitName) {
        pageVariablesStore.screen.unit.unityName = newUnitName;
        pageVariablesStore.setScreen({
          unit: pageVariablesStore.screen.unit,
          project: pageVariablesStore.screen.project,
          views: pageVariablesStore.screen.views
        });
      }
      resolve(res.result.data);
    });
  });
const getUnitIds = (arr, ids = []) => {
  arr.forEach(item => {
    if (item?.childs) {
      getUnitIds(item.childs, ids);
    }
    ids.push(item.id);
  });
  return ids;
};
const getUnitName = (arr, id) => {
  let unityName = "";
  arr.forEach(item => {
    if (item.id == id) {
      unityName = item.unityName;
      return unityName;
    } else {
      if (item.childs) {
        let newName = getUnitName(item.childs, id);
        unityName = newName != "" ? newName : unityName;
      }
    }
  });
  return unityName;
};
const logout = () => {
  removeToken();
  storageLocal().clear();
};
function usePageVariablesStoreHook() {
  return usePageVariablesStore(store);
}
export { PLATFORM_Map, UNIT_TYPE_VIEW_Map, logout, usePageVariablesStoreHook };
